from django.http import HttpResponseRedirect, HttpResponseNotFound, HttpResponseBadRequest
from django.shortcuts import render_to_response
from pottononline.classifieds.models import Ad
from datetime import datetime, timedelta
from forms import AdForm
from django.contrib.auth.decorators import login_required

def main(request):
    cutoff = datetime.now() - timedelta(14) # two weeks ago
    valid_ads = Ad.objects.filter(created__gt=cutoff)
    return render_to_response("classifieds/main.html", 
        {"ads": valid_ads, "user": request.user})

@login_required
def add(request):
    if request.method == "POST":
        form = AdForm(request.POST)
        if form.is_valid():
            ad = form.save()
            return HttpResponseRedirect("/classifieds/")
        else:
            return render_to_response("classifieds/add.html", {"form": form})
    elif request.method == "GET":
        return render_to_response("classifieds/add.html", {"form": AdForm()})

@login_required
def delete(request, adid):
    if request.method == "POST":
        try:
            ad = Ad.objects.get(pk=adid)
        except Ad.DoesNotExist:
            return HttpResponseNotFound("no such ad")
        if ad.user is None or \
           request.user.username != ad.user.username:
            return HttpResponseBadRequest("not your ad!")
        ad.delete()
        return HttpResponseRedirect("/classifieds/")
    else:
        return HttpResponseBadRequest

